package com.genesis.yunnanji.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.genesis.yunnanji.R;
import com.genesis.yunnanji.bean.AliPay;
import com.genesis.yunnanji.bean.CallBack;
import com.genesis.yunnanji.bean.PayResult;
import com.genesis.yunnanji.bean.StoreOrder;
import com.genesis.yunnanji.bean.WechatPay;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.Map;

import es.dmoral.toasty.Toasty;
import okhttp3.Call;

/**
 * 商城收银台
 * Created by Administrator on 2018/3/1.
 */

public class SelectPay extends BaseActivity {
    @ViewInject(R.id.tb_payment_toolbar)
    private Toolbar mToolbar;
    @ViewInject(R.id.tv_payment_id)
    private TextView tvNumber;
    @ViewInject(R.id.tv_payment_reciever)
    private TextView tvReciever;
    @ViewInject(R.id.tv_payment_count)
    private TextView tvCount;
    @ViewInject(R.id.rb_payment_weixin)
    private RadioButton wechat;
    @ViewInject(R.id.rb_payment_ali)
    private RadioButton ali;
    @ViewInject(R.id.rb_payment_balance)
    private RadioButton balance;
    @ViewInject(R.id.rb_payment_ecard)
    private RadioButton ecard;
    @ViewInject(R.id.bt_payment_pay)
    private Button btPay;
    @ViewInject(R.id.tv_balance_num)
    private TextView tvBalance;
    private String id;
    private IWXAPI msgApi;
    private static final int SDK_PAY_FLAG = 1;
    public static final int PAY_SUCCESS = 1;
    public static final int PAY_CANCEL = -1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_payment);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);

        msgApi = WXAPIFactory.createWXAPI(context, null);
//        msgApi.registerApp("wx9cf409e205703d74");//以前的
        msgApi.registerApp("wx9c0c7b1f3addd037");


        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        wechat.setChecked(true);
        id = getIntent().getStringExtra("id");
    }

    @Override
    protected void setUpView() {
        getCode();
    }

    @Event(value = {R.id.bt_payment_pay}, type = View.OnClickListener.class)
    private void click(View view) {
        switch (view.getId()) {
            case R.id.bt_payment_pay:
                if (wechat.isChecked()) {
                    WechatPay();
                } else if (ali.isChecked()) {
                    AliPay();
                } else if (balance.isChecked()) {
                    if (registerBean.getResult().getInfo().getCard_account() < registerBean.getResult().getInfo().getSubtotal()) {
                        Toasty.error(context, "余额不足！").show();
                    } else {
                        balance();
                    }
                } else if (ecard.isChecked()) {
                    Log.e("money", registerBean.getResult().getInfo().getSubtotal() + "");
                    Intent intent = new Intent(context, Ecard.class);
                    intent.putExtra("money", registerBean.getResult().getInfo().getSubtotal());
                    intent.putExtra("id", registerBean.getResult().getInfo().getOrderid());
                    startActivity(intent);
                }
                break;
        }
    }

    StoreOrder registerBean;


    private void getCode() {
        OkHttpUtils
                .get()
                .url(GenesisApiConfig.HOST + GenesisApiConfig.STORE_ORDER)
                .addParams("orderid", id)
                .addParams("__apptoken__", genesisUtils.getAppToken())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        Log.e("response", response);
                        registerBean = gson.fromJson(response, StoreOrder.class);
                        if (registerBean.getStatus() == 200) {
                            tvNumber.setText(registerBean.getResult().getInfo().getOrder_sn());
                            tvReciever.setText(registerBean.getResult().getInfo().getPickupname());
                            tvCount.setText(registerBean.getResult().getInfo().getSubtotal() + "");
                            tvBalance.setText(registerBean.getResult().getInfo().getCard_account() + "元");
                        } else {
                            Toasty.error(context, registerBean.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    private void WechatPay() {
        OkHttpUtils
                .get()
                .url(GenesisApiConfig.HOST + GenesisApiConfig.WECHATPAY)
                .addParams("orderid", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toasty.error(context, "数据获取失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        WechatPay wechatPay = gson.fromJson(response, WechatPay.class);
                        if (wechatPay.getStatus() == 200) {
                            PayReq request = new PayReq();
                            request.appId = wechatPay.getResult().getInfo().getAppid();
                            Log.e("lk", "onResponse: " + wechatPay.getResult().getInfo().getAppid());
                            request.partnerId = wechatPay.getResult().getInfo().getPartnerid();
                            request.prepayId = wechatPay.getResult().getInfo().getPrepayid();
                            request.packageValue = "Sign=WXPay";
                            request.nonceStr = wechatPay.getResult().getInfo().getNoncestr();
                            request.timeStamp = wechatPay.getResult().getInfo().getTimestamp();
                            request.sign = wechatPay.getResult().getInfo().getSign();
                            msgApi.sendReq(request);
                        } else {
                            Toasty.error(context, wechatPay.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    private void balance() {
        OkHttpUtils
                .get()
                .url(GenesisApiConfig.HOST + GenesisApiConfig.BALANCE)
                .addParams("orderid", id)
                .addParams("__apptoken__", genesisUtils.getAppToken())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        CallBack callBack = gson.fromJson(response, CallBack.class);
                        Log.e("response", response);
                        if (callBack.getStatus() == 200) {
                            Toasty.success(context, "支付成功", Toast.LENGTH_SHORT).show();
                            EventBus.getDefault().post(new String("success"));
                            finish();
                        } else {
                            Toasty.error(context, callBack.getMessage(), Toast.LENGTH_SHORT).show();
                        }

                    }
                });
    }


    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();

                    if (TextUtils.equals(resultStatus, "9000")) {

                        Toasty.success(context, "支付成功", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(new String("success"));
                        finish();
                    } else if (TextUtils.equals(resultStatus, "6001")) {

                        Toasty.info(context, "取消支付", Toast.LENGTH_SHORT).show();
                    } else {
                        Toasty.error(context, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };


    private void AliPay() {
        OkHttpUtils
                .get()
                .url(GenesisApiConfig.HOST + GenesisApiConfig.ALIPAY)
                .addParams("orderid", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toasty.error(context, "数据获取失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        final AliPay aliPay = gson.fromJson(response, AliPay.class);
                        if (aliPay.getStatus() == 200) {
                            Runnable payRunnable = new Runnable() {

                                @Override
                                public void run() {
                                    PayTask alipay = new PayTask(SelectPay.this);
                                    Map<String, String> result = alipay.payV2(aliPay.getResult().getResponse(), true);
                                    Log.e("msp", result.toString());
                                    Message msg = new Message();
                                    msg.what = SDK_PAY_FLAG;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            };

                            Thread payThread = new Thread(payRunnable);
                            payThread.start();

                        } else {
                            Toasty.error(context, aliPay.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    @Subscribe
    public void getEvent(String num) {
        Log.e("event", num);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
